package de.dlrg.wms.controller.controllers;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.synyx.hades.domain.Sort;
import org.synyx.hades.domain.Specification;

import de.dlrg.wms.controller.controllers.internalControllers.AutoAssignSwimmerController;
import de.dlrg.wms.controller.interfaces.ICRUD;
import de.dlrg.wms.dao.RunDao;
import de.dlrg.wms.dao.SwimmerTrackRunDao;
import de.dlrg.wms.model.Run;
import de.dlrg.wms.model.Track;

@Component
public class RunController implements ICRUD<Run> {
	@Autowired
	private CompetitionController competitionController;

	@Autowired
	private TrackController trackController;
	@Autowired
	private AgeClassController ageClassController;

	@Autowired
	private SwimmerTrackRunDao swimmerTrackRunDao;
	@Autowired
	private RunDao runDao;
	@Autowired
	private AutoAssignSwimmerController autoAssignSwimmerController;

	public List<Run> readAll() {
		return this.runDao.readAll(new Sort("runNo"));
	}

	public void createOrUpdate(List<Run> runsToCreateOrUpdate) {
		boolean isFirstRun = this.getTotalCount() <= 0;

		for (Run runToCreateOrUpdate : runsToCreateOrUpdate) {
			this.createOrUpdate(runToCreateOrUpdate);
		}
		if (isFirstRun) {
			this.competitionController.setFirstRun(runsToCreateOrUpdate.get(0));
		}
	}

	public void createOrUpdate(Run toCreateOrUpdate) {
		boolean isFirstRun = this.getTotalCount() <= 0;

		this.validate(toCreateOrUpdate);
		this.swimmerTrackRunDao.save(toCreateOrUpdate.getSwimmerTrackRun());
		this.runDao.save(toCreateOrUpdate);
		if (isFirstRun) {
			this.competitionController.setFirstRun(toCreateOrUpdate);
		}
	}

	public void delete(Run toDelete) {
		this.swimmerTrackRunDao.delete(toDelete.getSwimmerTrackRun());
		this.runDao.delete(toDelete);
	}

	public void validate(Run toValidate) {
		// TODO Auto-generated method stub

	}

	public int getNextRunNo() {
		int nextRunNo = 1;
		for(Run run : this.readAll()) {
			if(run.getRunNo()>nextRunNo) {
				nextRunNo = run.getRunNo();
			}
		}
		return nextRunNo +1;
	}

	public TrackController getTrackController() {
		return trackController;
	}

	public AgeClassController getAgeClassController() {
		return ageClassController;
	}

	public void autoAssignSwimmer() {
		this.runDao.deleteAll();
		this.swimmerTrackRunDao.deleteAll();
		List<Run> autoAssignedSwimmers = this.autoAssignSwimmerController
				.autoAssignSwimmer();
		this.createOrUpdate(autoAssignedSwimmers);
	}

	public int getTotalCount() {
		return this.runDao.readAll().size();
	}
}
